//
//  ADFourViewController.m
//  何五路
//
//  Created by _ADY on 15/8/25.
//  Copyright (c) 2015年 _ADY. All rights reserved.
//

#import "ADFourViewController.h"

@interface ADFourViewController ()

@end

#define sizeHight (screenMySize.size.width-30)/2

@implementation ADFourViewController
@synthesize mTableView,fListArray,stringId;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = bgColor;
    self.title = @"活动促销";
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;
    
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenMySize.size.width, screenMySize.size.height)];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mTableView];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];//清除多余分割线
    [mTableView setTableFooterView:v];
    
    __weak __typeof(self) weakSelf = self;
    
    mTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadNewData];
    }];
    mTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    pageForNumber = 1;
    fListArray = [[NSMutableArray alloc] init];
   
    [mTableView.header beginRefreshing];
}


- (void)loadNewData
{
    pageForNumber = 1;
    [self upDateTableView];
}
- (void)loadMoreData
{
    pageForNumber++;
    [self upDateTableView];
}

-(void)upDateTableView
{
    if ((pageForNumber-1)*itemLabel <= [fListArray count]||pageForNumber ==1)
    {
        NSMutableDictionary *postDic = [[NSMutableDictionary alloc] init];
        [postDic setObject:@"0" forKey:@"shopId"];
        if (stringId.length == 0) {
            [postDic setObject:@"0" forKey:@"categoryId"];
        }
        else
            [postDic setObject:stringId forKey:@"categoryId"];
        [postDic setObject:@"" forKey:@"searchKeyWord"];

        [postDic setObject:@"" forKey:@"subSearchKeyWord"];
        [postDic setObject:[NSNumber numberWithInt:pageForNumber] forKey:@"pageNumber"];
        [postDic setObject:[NSNumber numberWithInt:itemLabel] forKey:@"pageSize"];
        [postDic setObject:@"0" forKey:@"orderBy"];

        [postDic setObject:@"" forKey:@"specAttributes"];
        [postDic setObject:@"0" forKey:@"maxPrice"];
        [postDic setObject:@"0" forKey:@"minPrice"];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
            NSDictionary *ret = [SendService GetSearchProducts:postDic];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSLog(@"ret %@",ret);
  
                if (![[NSString stringWithFormat:@"%@",[ret objectForKey:@"Result"]] isEqualToString:@"error"])
                {
                    if (pageForNumber == 1)
                    {
                        if (fListArray != nil)
                        {
                            [fListArray removeAllObjects];
                            fListArray = nil;
                        }
                        fListArray = [[NSMutableArray alloc] init];

                    }
                    for (NSDictionary *pic in [[ret objectForKey:@"Entity"] objectForKey:@"ProductList"])
                    {
                        [fListArray addObject:pic];
                    }
                    
                }
                if (pageForNumber ==1)
                    [mTableView.header endRefreshing];
                else
                    [mTableView.footer endRefreshing];
                [mTableView reloadData];
                
            });
        });
        
    }
    else
    {
        [mTableView.footer noticeNoMoreData];
        [mTableView reloadData];
    }
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return fListArray.count/2+fListArray.count%2;;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60+sizeHight+5;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"search";
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        aTableView.showsVerticalScrollIndicator = NO;
    }
    cell.backgroundColor = [UIColor colorWithWhite:.95 alpha:1];
    int i = (int)[[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
        [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }
    return [self mCell:cell bCTableView:aTableView cellForRowAtIndexPath:indexPath];
    return cell;
}

- (UITableViewCell *)mCell:(UITableViewCell*)cell bCTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    for (int i = 0; i < 2; i++)
    {
        if (indexPath.row*2+i >= fListArray.count) {
            return cell;
        }
        
        NSDictionary *dic = [fListArray objectAtIndex:indexPath.row*2+i];
        
        UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10+i*(screenMySize.size.width-10)/2,5, sizeHight,sizeHight)];
        [bgImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[[dic objectForKey:@"DefaultPictureModel"]objectForKey:@"ImageUrl"]]]];
        bgImageView.contentMode =  UIViewContentModeScaleAspectFit;
        bgImageView.backgroundColor  = [UIColor whiteColor];
        [cell.contentView addSubview:bgImageView];
        
        NSString *nameString = nil;
        NSString *ordPrice = nil;
        NSString *Price = nil;

        nameString = [NSString stringWithFormat:@"%@",[dic objectForKey:@"Name"]];
        ordPrice = [NSString stringWithFormat:@"%@",[[dic objectForKey:@"ProductPrice"] objectForKey:@"OldPrice"]];
        Price = [NSString stringWithFormat:@"%@",[[dic objectForKey:@"ProductPrice"] objectForKey:@"Price"]];

        [cell.contentView addSubview:[self setFrame:CGRectMake(bgImageView.frame.origin.x, bgImageView.frame.origin.y+sizeHight, sizeHight, 40) setTitle:nameString setFont:labelSize setColor:[UIColor grayColor]]];
        //
        
        
        if ([[NSString stringWithFormat:@"%@",ordPrice] isEqualToString:@"<null>"]) {
            [cell.contentView addSubview:[self setFrame:CGRectMake(bgImageView.frame.origin.x, bgImageView.frame.origin.y+sizeHight+40, sizeHight, 20) setTitle:Price setFont:labelSize setColor:[UIColor redColor]]];
        }
        else
        {
            UICustomLineLabel *mlabel = [[UICustomLineLabel alloc] init];
            mlabel.frame = CGRectMake(bgImageView.frame.origin.x, bgImageView.frame.origin.y+sizeHight+40, sizeHight/2, 20);
            mlabel.lineType = LineTypeMiddle;
            mlabel.textColor = [UIColor redColor];
            mlabel.lineColor = [UIColor redColor];
            mlabel.font = [UIFont fontWithName:@"Arial" size:labelSize-2];
            mlabel.text = ordPrice;
            [cell.contentView addSubview:mlabel];
            
            UICustomLineLabel *mlabel1 = [[UICustomLineLabel alloc] init];
            mlabel1.frame = CGRectMake(bgImageView.frame.origin.x+sizeHight/2, bgImageView.frame.origin.y+sizeHight+40, sizeHight/2, 20);
            mlabel1.lineType = LineTypeNone;
            mlabel1.textColor = [UIColor redColor];
            mlabel1.lineColor = [UIColor redColor];
            mlabel1.font = [UIFont fontWithName:@"Arial" size:labelSize];
            mlabel1.text = Price;
            [cell.contentView addSubview:mlabel1];
            
        }
        
        
        UIButton *bgButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [bgButton setFrame:CGRectMake(10+i*(screenMySize.size.width-10)/2,5, sizeHight,sizeHight+60)];
        [bgButton addTarget:self action:@selector(gotoAction:) forControlEvents:UIControlEventTouchUpInside];
        bgButton.tag =indexPath.row*2+i+1000;
        [cell.contentView addSubview:bgButton];
    }
    
    return cell;
}

-(void)gotoAction:(id)sender
{
    int type = ((UIButton*)sender).tag -1000;
    GoodsDetailsViewController *details = [[GoodsDetailsViewController alloc] init];
    details.productId = [NSString stringWithFormat:@"%@",[[[fListArray objectAtIndex:type] objectForKey:@"ReviewOverviewModel"] objectForKey:@"ProductId"]];

    details.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:details animated:YES];
}

-(UILabel*)setFrame:(CGRect)frame setTitle:(NSString*)title setFont:(int)font setColor:(UIColor*)myColor
{
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:frame];
    if (title != nil)
        titleLabel.text = [NSString stringWithFormat:@"%@",title];
    titleLabel.textAlignment = 0;
    titleLabel.numberOfLines = 0;
    titleLabel.font = [UIFont fontWithName:@"Arial" size:font];
    titleLabel.textColor = myColor;
    return titleLabel;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
